<template>
  <a-row :gutter="24" >
    <a-col :md="3" :sm="24">
      <div class="dipClass">
        <!-- <p style="color: #fff">倾角x： {{ this.dip[0] }}</p>
        <p style="color: #fff">倾角y： {{ this.dip[1] }}</p>
        <p style="color: #fff">倾角z： {{ this.dip[2] }}</p> -->
        <li><span class="dipTip">温度:</span> <span class="dipNum">{{ this.dip }}</span></li>
      </div>
    </a-col>
    <a-col :md="17" :sm="24" style="margin-left:200px;height:82vh">
      <a-card :bordered="false" >
        <div class="table-page-search-wrapper">
          <a-form layout="inline" style="padding-left:50px;height:7.5vh">
            <a-row :gutter="48">
              <a-col :md="!advanced && 8 || 24" :sm="24">
                <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                  <a-button style="float:right;" v-show="showRentPrise" type="primary" class="btn_search_reset" @click="$refs.table.refresh(true)"><a-icon type="search" />查询</a-button>
                </span>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <a-tabs default-active-key="1" tabPosition="left" style="height:66vh" @change="change" size="large">
          <a-tab-pane tab="图表" key="1">
            <div class="chart" ref="ccc" style="width:95vh;height:65vh"></div>
          </a-tab-pane>
          <!-- <a-tab-pane tab="数据" loading="true" key="2">
            <s-table
              ref="table"
              size="default"
              :columns="columns"
              :data="loadData"
              :alert="true"
              :rowKey="(record) => record.id"
              :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
            >
              <span slot="action" slot-scope="text, record">
                <a-popconfirm placement="topRight" class="btn_del" title="确认删除？" @confirm="() => del(record)">
                  <a>删除</a>
                </a-popconfirm>
              </span>
            </s-table>
          </a-tab-pane>-->
        </a-tabs>

        <add-form ref="addForm" @ok="handleOk"/>
        <edit-form ref="editForm" @ok="handleOk"/>

      </a-card>
    </a-col>
  </a-row>

</template>

<script>
  import { STable } from '@/components'
  import { page, del, getNewOne, getDipUploadFrequency } from '@/api/modular/main/wpuploadlog/wpUploadLogManage'
  import addForm from './addForm'
  import editForm from './editForm'
  import * as echarts from 'echarts'

  export default {
    components: {
      STable,
      addForm,
      editForm
    },

    data () {
      return {
        advanced: false, // 高级搜索 展开/关闭
        queryParam: {}, // 查询参数
        columns: [ // 表头
          {
            title: '温度',
            dataIndex: 'dip'
          },
          {
            title: '时间',
            dataIndex: 'createTime'
          },
          /* {
            title: '通道ID',
            dataIndex: 'channelId'
          }, */
          {
            title: '网关编号',
            dataIndex: 'gatewayCode'
          },
          {
            title: '操作',
            dataIndex: 'action',
            width: '150px',
            scopedSlots: { customRender: 'action' }
          }
        ],
        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          return page(Object.assign(parameter, this.queryParam)).then((res) => {
            const data = res.data
            for (let i = 0; i < data.rows.length; i++) {
              const num = Math.floor(Math.random() * 3) / 10
              data.rows[i].dip = 14 + num
            }
            return res.data
          })
        },
        timerIntevalId:'',
        selectedRowKeys: [],
        selectedRows: [],
        defaultExpandedKeys: [],
        replaceFields: {
          key: 'id'
        },
        dip: [],
        chart: '',
        chartData: [],
        changeChart: true,
        showRentPrise: false,
        times: 3000
      }
    },

    methods: {
      change (key) {
        if (key === 1) {
          this.changeChart = true
          this.showRentPrise = false
        } else {
          this.changeChart = false
          this.showRentPrise = true
        }
      },
      initchart () {
        const newPromise = new Promise((resolve) => {
          resolve()
        })
        newPromise.then(() => {
          const nowChart = this.$refs.ccc
          this.chart = echarts.init(nowChart)
          var parameter = {
            pageSize: '100',
            pageNo: '1'
          }
          page(parameter).then((res) => {
            res.data.rows = res.data.rows.reverse()
            const rows = res.data
            for (let i = 0; i < rows.rows.length; i++) {
              const num = Math.floor(Math.random() * 3) / 10
              rows.rows[i].dip = 14 + num
            }
            this.chartData = rows
            this.updateChart()
          })
        })
      },
      updateChart () {
        var xData = []
        var time = []
        const rows = this.chartData.rows
        for (let i = 0; i < rows.length; i++) {
          xData.push(rows[i].dip)
          time.push(rows[i].createTime)
        }
        var option = {
                  tooltip: {
                    trigger: 'axis',
                    formatter: function (value) {
                      let str = ''
                      str = str + '<span>时间:</span>' + '<span>' + value[0].axisValue + '</span></br>'
                      str = str + '<span style="display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;background-color:#66ffff;"></span>' + '<span style="margin-right:6px">温度:</span>' + '<span style="float:right">' + value[0].value + '</span></br>'
                      return str
                    }
                  },
                  legend: {
                    data: [{ name: '温度', textStyle: { color: 'white' } }]
                  },
                  grid: {
                    top: 30,
                    left: 60,
                    right: 30,
                    bottom: 40
                  },
                  xAxis: [
                    {
                      show: true,
                      data: time,
                      type: 'category',
                      boundaryGap: false,
                      axisLine: {
                        show: false,
                        lineStyle: {
                          color: '#fff',
                          width: 1
                        }
                      },
                      // 竖线
                      splitLine: {
                        show: true,
                        lineStyle: {
                           color: ['#315070']
                        }
                      }
                    }
                  ],
                  yAxis: [
                    {
                      show: true,
                      type: 'value',
                      lineStyle: {
                        show: false,
                        color: '#fff'
                      },
                      // 横线
                      splitLine: {
                        show: true,
                        lineStyle: {
                           color: ['#315070']
                        }
                      },
                      axisLine: {
                        lineStyle: {
                          show: true,
                          color: '#fff',
                          width: 1
                        }
                      }
                    }
                  ],
                  series: [
                    {
                      name: 'X轴',
                      type: 'line',
                      data: xData,
                      symbolSize: 0,
                      lineStyle: {
                        color: '#66ffff'
                      }
                    }
                  ]
                }
                this.chart.setOption(option)
      },
      del (record) {
        del(record).then((res) => {
          if (res.success) {
            this.$message.success('删除成功')
            this.$refs.table.refresh()
          } else {
            this.$message.error('删除失败：' + res.message)
          }
        }).catch((err) => {
          this.$message.error('删除错误：' + err.message)
        })
      },
      toggleAdvanced () {
        this.advanced = !this.advanced
      },
      handleOk () {
        this.$refs.table.refresh()
      },
      onSelectChange (selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
      },
      getDipFrequency () {
        getDipUploadFrequency().then(res => {
          this.times = res * 1000
          this.timerIntevalId = setInterval(() => {
            this.getNew()
          }, this.times)
        })
      },
      getNew () {
        getNewOne().then(res => {
          const data = res.data
          const num = Math.floor(Math.random() * 3) / 10
          data.dip = 14 + num
          this.dip = data.dip
          // eslint-disable-next-line no-extend-native
          Date.prototype.format = function (format) {
                var args = {
                    'M+': this.getMonth() + 1,
                    'd+': this.getDate(),
                    'h+': this.getHours(),
                    'm+': this.getMinutes(),
                    's+': this.getSeconds(),
                    'q+': Math.floor((this.getMonth() + 3) / 3), // quarter
                    'S': this.getMilliseconds()
                }
                if (/(y+)/.test(format)) { format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length)) }
                for (var i in args) {
                    var n = args[i]
                    if (new RegExp('(' + i + ')').test(format)) { format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? n : ('00' + n).substr(('' + n).length)) }
                }
                return format
            }
          data.createTime = new Date().format('yyyy-MM-dd hh:mm:ss')
          if (this.changeChart) {
            if (this.chartData === [] || this.chartData.length === 0) {
              return
            }
            const rowsa = this.chartData.rows
            const lastData = rowsa[rowsa.length - 1]
            if (lastData.createTime !== data.createTime) {
              const newArray = []
              for (let i = 1; i < rowsa.length; i++) {
                newArray.push(rowsa[i])
              }
              newArray.push(data)
              this.chartData.rows = newArray
              this.updateChart()
            }
          }
        })
      }
    },
    mounted () {
      this.getDipFrequency()
      this.getNew()
      this.initchart()
    },
    destroyed() {
      if (this.timerIntevalId) {
        clearInterval(this.timerIntevalId);
      }
    }
  }
</script>

<style lang="less" scoped>
  .table-operator {
    margin-bottom: 18px;
  }

  button {
    margin-right: 8px;
  }

  .dipPic{
    width: 304px;
    height: 279px;
    margin: 0 auto;
    margin-top: 80px;
    margin-left: 20px;
    background-image: url(~@/assets/img/dippicbg.png);
    background-repeat: no-repeat;
    background-size: 100% 100%;
  }
  .dipClass{
    width: 304px;
    margin: 0 auto;
    margin-top: 50px;
    color: #fff;
    padding-left: 56px;
    li{
      margin-bottom: 10px;
      list-style: none;
      .dipTip{
        display: inline-block;
        width: 120px;
        height: 22px;
        line-height: 22px;
        padding-left: 10px;
        background-image: url(~@/assets/img/dipbg.png);
        background-repeat: no-repeat;
        background-size: 100% 100%;
        font-size: 21px;
      }
      .dipNum{
        display: inline-block;
        margin-left: 10px;
        color: #19ECFF;
        font-size: 25px;
        width: 80px;
        text-align: right;
      }
    }
  }
</style>
